package com.java.netty.nio.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * @Author: Dgg
 * @Date: 2021/12/23 20:36
 * SimpleChannelInboundHandler 是ChannelInboundHandlerAdapter的子类
 * HttpObject 客户端和服务端相互通信的数据被封装成httpObject
 */
public class TestHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {
	//读取客户端数据
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
		System.out.println("消息监听");
		//判断msg 是不是一个httpRequest
		if (msg instanceof HttpRequest) {
			System.out.println("msg 类型 =" + msg.getClass());
			System.out.println("客户端地址 =" + ctx.channel().remoteAddress());

			HttpRequest httpRequest = (HttpRequest) msg;
			URI uri = new URI(httpRequest.uri());
			if ("/favicon.ico".equals(uri.getPath())) {
				System.out.println("请求了图标");
				return;
			}
			//回复 浏览器信息 [http 协议]
			ByteBuf context = Unpooled.copiedBuffer("hello,我是服务器", CharsetUtil.UTF_8);

			//构造一个HTTP响应
			FullHttpResponse defaultFullHttpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, context);
			defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
			defaultFullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, context.readableBytes());

			//将 构建好的response 返回

			ctx.writeAndFlush(defaultFullHttpResponse);

		}
	}
}
